/**
 * <template>
  <div>
    <input type="file" @change="handleFileChange" accept="image/*" />
    <p v-if="compressedFile">压缩后的文件大小: {{ compressedFile.size }} 字节</p>
    <img v-if="compressedFileUrl" :src="compressedFileUrl" alt="Compressed Image" />
    <p v-if="uploadStatus">{{ uploadStatus }}</p>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      compressedFile: null, // 压缩后的文件
      compressedFileUrl: "", // 压缩后的图片 URL
      uploadStatus: "", // 上传状态
    };
  },
  methods: {
    // 处理文件选择
    async handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        try {
          // 压缩图片
          const compressedBlob = await this.compressImage(file, 800, 0.75); // 压缩到 800px 宽度，质量 75%
          this.compressedFile = compressedBlob;
          this.compressedFileUrl = URL.createObjectURL(compressedBlob); // 生成 Blob URL
          console.log("Compressed file size:", compressedBlob.size);

          // 上传图片
          this.uploadStatus = "正在上传...";
          const response = await this.uploadImage(compressedBlob);
          this.uploadStatus = "上传成功: " + response.data.message;
        } catch (error) {
          console.error("Failed to compress or upload image:", error);
          this.uploadStatus = "上传失败: " + error.message;
        }
      }
    },

    // 图片压缩函数
    compressImage(file, maxWidth = 800, quality = 0.75) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = URL.createObjectURL(file);

        img.onload = () => {
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");

          // 计算压缩后的尺寸
          let width = img.width;
          let height = img.height;
          if (width > maxWidth) {
            const ratio = maxWidth / width;
            width = maxWidth;
            height = height * ratio;
          }

          // 设置 canvas 尺寸
          canvas.width = width;
          canvas.height = height;

          // 绘制图片到 canvas
          ctx.drawImage(img, 0, 0, width, height);

          // 将 canvas 转换为 Blob
          canvas.toBlob(
            (blob) => {
              if (blob) {
                resolve(blob);
              } else {
                reject(new Error("Failed to compress image"));
              }
            },
            "image/jpeg", // 输出格式
            quality // 图片质量（0 到 1）
          );
        };

        img.onerror = (error) => {
          reject(error);
        };
      });
    },

    // 上传图片函数
    async uploadImage(blob) {
      const formData = new FormData();
      formData.append("file", blob, "compressed-image.jpg"); // 将 Blob 添加到 FormData

      // 发送请求
      const response = await axios.post("https://example.com/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data", // 设置请求头
        },
      });

      return response;
    },
  },
};
</script>

<style scoped>
img {
  max-width: 100%;
  height: auto;
  margin-top: 20px;
}
</style>
 */
/**
 * 图片压缩函数
 * @param {*} file 
 * @param {*} maxWidth 
 * @param {*} quality 
 * @returns 
 */
export function compressImage(file, maxWidth = 800, quality = 0.75) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = URL.createObjectURL(file);

    img.onload = () => {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");

      // 计算压缩后的尺寸
      let width = img.width;
      let height = img.height;
      if (width > maxWidth) {
        const ratio = maxWidth / width;
        width = maxWidth;
        height = height * ratio;
      }

      // 设置 canvas 尺寸
      canvas.width = width;
      canvas.height = height;

      // 绘制图片到 canvas
      ctx.drawImage(img, 0, 0, width, height);

      // 将 canvas 转换为 Blob
      canvas.toBlob(
        (blob) => {
          if (blob) {
            resolve(blob);
          } else {
            reject(new Error("Failed to compress image"));
          }
        },
        "image/jpeg", // 输出格式
        quality // 图片质量（0 到 1）
      );
    };

    img.onerror = (error) => {
      reject(error);
    };
  });
}

